package zzl.io;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName ClientSocket
 * @Description java socket解决半包、粘包的问题。固定分割符号
 * @Author zhangzeli
 * @Version 1.0
 * @Date 2019/2/27-15:22
 **/
public class ClientSocket_v1 {
    public static void main(String[] args) throws IOException, InterruptedException{
        new SocketServer().start();
        new SocketClient().start();
//        readFileByBytes("D:\\ideawork\\zookeepertest\\src\\main\\resources\\log4j.properties");
    }

    static class SocketClient extends Thread {
        Socket clientSocket = new Socket();

        public SocketClient() throws IOException {
            clientSocket.connect(new InetSocketAddress(8089));
        }

        public void run() {
            String reqMessage = "HelloWorld！ from clientsocket this is test half packages我是汉字!\r\n";
            try {
                for (int i = 0; i < 10; i++) {
                    OutputStream os = clientSocket.getOutputStream();
                    os.write(reqMessage.getBytes());
                    System.out.println("send message =》" + i + " " + reqMessage.replaceAll("\r\n",""));
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (clientSocket != null) {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    static class SocketServer extends Thread {
        ServerSocket serverSocket;

        public SocketServer() {
            try {
                serverSocket = new ServerSocket();
                serverSocket.bind(new InetSocketAddress(8089));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public void run() {
            int count = 0;
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            List<Byte> l = new LinkedList<Byte>();
            int n =0;
            while (true) {
                try {
                    InputStream reader = socket.getInputStream();
                    count = reader.read();
                    if (count > 0) {
                        Byte aByte = Byte.valueOf((byte) count);
                        l.add(aByte);

                        //表示還沒有读完   但是先看包里面数据
                        String s = new String(tran(l));
//                        System.out.println(s);
                        if(s.contains("\r\n")){
                            System.out.println("receive data from client:" +n + s.replaceAll("\r\n",""));
                            n++;
                            l.clear();
                        }
//                        System.out.println("receive data from client:" + receivBuffer.toString());
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte [] tran(List<Byte> l ){
        byte [] s = new byte[l.size()];
        for(int i = 0 ;i<s.length;i++){
            s[i] = l.get(i);
        }
        return s;
    }


    /**
     * 以字节为单位读取文件，常用于读二进制文件，如图片、声音、影像等文件。
     */
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容，一次读一个字节：");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

    }
}
